"use strict";
// Class definition

var postStandardAdd = function () {
    var configTableId = '#standard-config';

    var eventHandler = function () {
        $(document).off('show.bs.modal', '#org-select');
        $(document).on('show.bs.modal', '#org-select', initOrgSelectModal);

        $(document).off('show.bs.modal', '#select-dataSet');
        $(document).on('show.bs.modal', '#select-dataSet', initDataSetSelect);

        $(document).off('changed.bs.select', 'select[name="postName"]');
        $(document).on('changed.bs.select', 'select[name="postName"]', onChangePost);

        $(document).off('changed.bs.select', 'select[name="areaNames"]');
        $(document).on('changed.bs.select', 'select[name="areaNames"]', onChangeArea);

        $(document).off('click', '.standard-config-form .save-btn');
        $(document).on('click', '.standard-config-form .save-btn', saveStandardConfig);
    };

    /**
     * 初始化组织树摸态框
     * @param e
     */
    var initOrgSelectModal = function (e) {
        var options = {};
        options.url = '../../json/standard/org-tree.json';
        options.allowLevelIcons = ['operating_area', 'station', 'device'];
        options.relatedTarget = e.relatedTarget;
        KOrgSelect.init(options);
    };

    /**
     * 初始化数据集选择
     * @param e
     */
    var initDataSetSelect = function (e) {
        var options = {};
        options.url = '/default/json/base-info/post-standard-manage/dataSet.json';
        options.allowLevelIcons = ['materials'];
        options.relatedTarget = e.relatedTarget;
        options.orgSelectId = '#select-dataSet';
        options.treeId = 'dataSet-tree';
        KOrgSelect.init(options);

        // TODO 替换组织选择的确认事件绑定
        $(document).off('click', '#select-dataSet .confirm-btn');
        $(document).on('click', '#select-dataSet .confirm-btn', confirmDataSetSelect);
    };

    /**
     * 数据集选择后的确认按钮事件
     */
    var confirmDataSetSelect = function () {
        var $dataSetModal =  $('#select-dataSet');
        var zTreeObj = $.fn.zTree.getZTreeObj('dataSet-tree');
        var checkedNode = zTreeObj.getCheckedNodes(true);
        var dataSetItem = [];
        checkedNode.forEach(function (item, index) {
            if (item.iconSkin === 'materials') {
                item.dataItemId = item.id;
                dataSetItem.push(item);
            }
        });

        standardConfig.appendDataSet($('.data-item-config'), dataSetItem);
        $dataSetModal.modal('hide');
    };

    /**
     * 岗位变更的事件处理
     * @returns {Promise<void>}
     */
    var onChangePost = async function () {
        var postId = $(this).val();
        var url = 'default/json/base-info/post-standard-manage/area-data.json';
        var params = {
            postId: postId
        };
        var res = await KHttp.get(url, params);
        if (res && res.data) {
            var $areaNames = $('select[name="areaNames"]');
            $areaNames.empty();
            res.data.forEach(function (item) {
                $areaNames.append('<option value="'+ item.areaId +'">'+ item.areaName +'</option>');
                $areaNames.find('[value="'+ item.areaId +'"]').data('dataList', item.dataList);
            });
            $areaNames.selectpicker('refresh');
        }
    };

    /**
     * 区域变更的事件处理
     * @returns {Promise<void>}
     */
    var onChangeArea = function () {
        var areaIds = $(this).val();
        var $areaNames = $('select[name="areaNames"]');
        var $table = $(configTableId);
        var tableData = [];
        areaIds.forEach(function (areaId, index) {
            var dataList = $areaNames.find('[value="'+ areaId +'"]').data('dataList');
            dataList.forEach(function (row) {
                // TODO 复制对象，解决合并单元格错乱的问题
                var newRow = JSON.parse(JSON.stringify(row));
                newRow.num = index + 1;
                tableData.push(newRow);
            });
        });

        $table.bootstrapTable('load', tableData);
    };

    /**
     * 保存岗位标准配置
     */
    var saveStandardConfig = function () {
        standardConfig.getConfigData(function (data) {
            console.log(data);
        });
    };

    var initStandardTable = async function () {
        var url = 'default/json/base-info/post-standard-manage/standard-table.json';
        var params = {};
        var res = await KHttp.get(url, params);
        if (res && res.data) {
            standardConfig.init($(configTableId), {
                // editable: false,
                // data: res.data,
                data: []
            });
        }
    };

    return {
        // public functions
        init: async function() {
            eventHandler();
            $('.k_selectpicker').selectpicker();
            await initStandardTable();
        }
    };
}();

jQuery(document).ready(function() {
    postStandardAdd.init();
});